<script setup>
import dayjs from "dayjs";
import Calendar from "mpvue-calendar";
import { ElMessage } from 'element-plus'
import {
  ref,
  computed,
  onMounted,
  getCurrentInstance
} from "vue";
import { useRouter, useRoute } from "vue-router";
let { proxy } = getCurrentInstance();
let router = useRouter();
let route = useRoute();
// 请求的已经预订过得日期
let showday = ref([]);
// 路由跳转hid得到价格
let price = ref(335);
const value = ref([]);
const people = [
  {
    value: "成人",
    label: "成人",
  },
  {
    value: "儿童",
    label: "儿童(2-12)",
  },
  {
    value: "婴儿",
    label: "婴儿(2岁以下)",
  },
];
let adultnum = ref(1);
let childnum = ref(0);
let babynum = ref(0);
// 路由跳转id得到最大入住人数
let peoplenummax = ref(0);
let renttime = [];
// 已知开始日期和结束日期获取期间所有日期
const format = (time) => {
  let ymd = "";
  let mouth =time.getMonth() + 1 >= 10? time.getMonth() + 1: "0" + (time.getMonth() + 1);
  let day = time.getDate() >= 10 ? time.getDate() : "0" + time.getDate();
  ymd += time.getFullYear() + "-"; // 获取年份。
  ymd += mouth + "-"; // 获取月份。
  ymd += day; // 获取日。
  return ymd; // 返回日期。
};
// 已知开始日期和结束日期获取所有天数
const getAllDate = (start, end) => {
  let dateArr = [];
  let startArr = start.split("-");
  let endArr = end.split("-");
  let db = new Date();
  db.setUTCFullYear(startArr[0], startArr[1] - 1, startArr[2]);
  let de = new Date();
  de.setUTCFullYear(endArr[0], endArr[1] - 1, endArr[2]);
  let unixDb = db.getTime();
  let unixDe = de.getTime();
  let stamp;
  const oneDay = 24 * 60 * 60 * 1000;
  for (stamp = unixDb; stamp <= unixDe; ) {
    dateArr.push(format(new Date(parseInt(stamp))));
    stamp = stamp + oneDay;
  }
  return dateArr;
};
let handleChangeadult = (value) => {
  adultnum.value = value;
};
const handleChangechild = (value) => {
  childnum.value = value;
};
const handleChangebaby = (value) => {
  babynum.value = value;
};
let tianshu = ref(0);
let clear = (val) => {
  if (val == "成人") {
    adultnum.value = 1;
  } else if (val == "儿童") {
    childnum.value = 0;
  } else if (val == "婴儿") {
    babynum.value = 0;
  }
};
let day = (value) => {
  if (value == undefined) {
    return;
  }
  renttime = value;
  if (value[0]) {
    let sdate = new Date(value[0]);
    let now = new Date(value[1]);
    let days = now.getTime() - sdate.getTime();
    tianshu.value = parseInt(days / (1000 * 60 * 60 * 24));
    console.log(tianshu.value);
  }
};
let total = computed(() => {
  console.log(tianshu.value);
  return price.value * tianshu.value + 50;
});
onMounted(async () => {
  let result = await proxy.$axios("/houseinformationrequest?hid=6");
  price.value = result.data.info[0].price;
  peoplenummax.value = result.data.info[0].peonum;
});

// 将日期转换为2022-1-8，去掉0的方法
let dislodgeZero=(str)=>{
			    let strArray = str.split('-');
			    strArray = strArray.map(function(val) {
			        if (val[0] == '0') {
			            return val = val.slice(1);
			        }else{
			            return val;
			        }
			    })
			    return strArray.join('-');
			}

onMounted(async () => {
  let result = await proxy.$axios("/housecanrenttimerequest?hid=6");
  let objarr = [];
  let objarr1 = [];
  for (let j = 0; j < result.data.info.length; j++) {
    objarr.push(result.data.info[j].canrenttime.split(","));
  }
  objarr.forEach((el) => {
    el.forEach((el) => {
      el=dislodgeZero(el);
      objarr1.push(el);
    });
  });
  // console.log(objarr1);
  showday.value = objarr1;
});
// 提交订单没有登录就让其登录
let sumbitorder = () => {
  let token = localStorage.getItem("token");
  let renshu = adultnum.value + childnum.value;
  let peoplenum = `${renshu}人，${babynum.value}名婴儿`;
  let allday='';
  // console.log(renttime==='')
  if (renttime[0]) {
    allday = getAllDate(renttime[0], renttime[1]);
    allday = allday.slice(0, allday.length - 1);
    let obj = { renttime: allday.toString(), peoplenum, token, hid: 6 ,total:price.value * tianshu.value + 50};
    router.push({ path: "/tenant", query: { ...obj } });
  }else if(!renttime[0]){
    ElMessage({
    showClose: true,
    message: '请先选择预订日期才能预订',
    type: 'warning',
  });
  }
};
</script>

<template>
  <div>
    <h1>房源预订</h1>
    <el-row :gutter="20">
      <el-col :span="12">
        <h2 class="priceinline">￥{{ price }}</h2>
        <span>/晚</span>
        <el-divider />
        <p>日期：请参考右侧日历，灰色表示已经预订过，请不要选择</p>
        <a-range-picker
          style="width: 360px; margin-right: 24px; margin-bottom: 24px"
          :disabledDate="(current) => dayjs(current).isBefore(dayjs())"
          @change="day"
        />
        <el-divider />
        <p>人数</p>
        <p>入住最多人数：{{ peoplenummax }}人，婴儿不包括在内，最多5个</p>
        <el-select
          v-model="value"
          placeholder="1人"
          multiple
          collapse-tags
          collapse-tags-tooltip
          @remove-tag="clear"
        >
          <el-option :value="people[0].value">
            <span style="float: left">{{ people[0].label }}</span>
            <span style="float: right">
              <el-input-number
                v-model="adultnum"
                :min="1"
                :max="peoplenummax"
                @change="handleChangeadult"
              />
            </span>
          </el-option>
          <el-option :value="people[1].value">
            <span style="float: left">{{ people[1].label }}</span>
            <span style="float: right">
              <el-input-number
                v-model="childnum"
                :min="0"
                :max="peoplenummax"
                @change="handleChangechild"
              />
            </span>
          </el-option>
          <el-option :value="people[2].value">
            <span style="float: left">{{ people[2].label }}</span>
            <span style="float: right">
              <el-input-number
                v-model="babynum"
                :min="0"
                :max="5"
                @change="handleChangebaby"
              />
            </span>
          </el-option>
        </el-select>
        <el-divider />
        <el-row :gutter="20">
          <el-col :span="16"
            ><p>￥{{ price }} x 1晚</p></el-col
          >
          <el-col :span="8"
            ><p>￥{{ price }}</p></el-col
          >
        </el-row>
        <el-divider />
        <el-row :gutter="20">
          <el-col :span="16">
            <span>清洁费</span>
            <el-tooltip
              effect="dark"
              content="服务费用于帮助我们维护平台的运营，同时为您的行程提供专业的客服帮助。"
              placement="right-start"
            >
              <el-icon style="color: green"><QuestionFilled /></el-icon>
            </el-tooltip>
          </el-col>
          <el-col :span="8"><span>￥50</span></el-col>
        </el-row>
        <el-divider />
        <el-row :gutter="20">
          <el-col :span="16"><h3>总价</h3></el-col>
          <el-col :span="8"
            ><p>￥{{ total }}</p></el-col
          >
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-button type="danger" style="width: 100%" @click="sumbitorder"
              >预订</el-button
            >
          </el-col>
        </el-row>
      </el-col>
      <el-col :span="12" class="calender"
        ><Calendar backgroundText class-name="select-mode" :disabled="showday"
      /></el-col>
    </el-row>
  </div>
</template>

<style scoped lang='scss'>
.priceinline {
  display: inline-block;
}
.calender {
  margin-top: 170px;
}
</style>